import path from 'path'
import fs from 'fs-extra'
import less from 'less'
import CleanCss from 'clean-css'
import glob from 'glob'
import paths from './paths'

export const buildStyle = async () => {
  // 拷贝less文件到目标文件，index.less编译生成index.css
  const files = glob.sync('**/*.less', {
    cwd: paths.components,
  })

  for (const filename of files) {
    const absolute = paths.resolvePath(`src/${filename}`)
    fs.copySync(absolute, paths.resolvePath(`../../dist/style/${filename}`))

    if (/index\.less$/.test(filename)) {
      console.log(`building ${filename}`)

      const lessContent = fs.readFileSync(absolute, 'utf8')
      less.render(
        lessContent,
        {
          filename,
          paths: [paths.resolvePath(`src/${path.dirname(filename)}`), paths.root],
        },
        (err, result) => {
          if (err) {
            console.log(err)
          } else if (result && result.css) {
            const cssFilename = filename.replace('.less', '.css')
            fs.writeFileSync(paths.resolvePath(`../../dist/style/${cssFilename}`), result.css)
            console.log(`${filename} build success`)
          }
        }
      )
    }
  }

  // 拷贝并编译less入口文件
  console.log('build target css')
  const indexLessPath = paths.resolvePath('src/index.less')
  fs.copySync(indexLessPath, paths.resolvePath('../../dist/style/index.less'))

  const indexLess = fs.readFileSync(indexLessPath, 'utf8')
  const result = await less.render(indexLess, {
    paths: [paths.components],
  })

  const compress = new CleanCss().minify(result.css)
  fs.writeFileSync(paths.resolvePath('../../dist/style/index.min.css'), compress.styles)
  console.log(`target build success`)
}
